package http;

import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

public class HttpServer {
	public static void main(String[] args) {
		try {
			ServerSocket st = new ServerSocket(8888);
			while (true) {
				new SocketThread(st.accept()).start();

			}
		} catch (IOException e) {

			e.printStackTrace();
		}

	}
}
//ngrok
class SocketThread extends Thread {
	private Socket s;

	public SocketThread(Socket accept) {

		this.s = accept;
	}

	@Override
	public void run() {
		System.out.println(s + "开始连接了");
		final String basepath = "E:\\WORKSPACES\\hbuilderproj\\java63front";
		try {
			InputStream in = s.getInputStream();
			OutputStream out = s.getOutputStream();
			PrintWriter pw = new PrintWriter(out);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String str = null, file = null;
			System.out.println("读取请求头");
			while ((str = br.readLine()).length() > 0) {
				System.out.println(str);
				if (str.startsWith("GET")) {
					file = str.split(" ")[1];
					System.out.println("path=" + file);
				}
			}
			File f = new File(basepath, file);
			long len = f.length();
			StringBuffer sb = new StringBuffer();
			sb.append("HTTP/1.1 200 OK\r\n");

			sb.append("Cache-Control: private" + "\r\n");
			sb.append("Content-Length: " + len + "\r\n");
			sb.append("Content-Type: text/html; charset=utf-8" + "\r\n");
			sb.append("Server: Laoliu-server/99" + "\r\n");
			// X-AspNet-Version: 2.0.50727
			// X-Powered-By: ASP.NET

			Calendar cd = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
			sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // ����ʱ��ΪGMT
			String dstr = sdf.format(cd.getTime());
			// System.out.println(str);
			sb.append("Date: " + dstr + "\r\n");
			pw.println(sb);
			pw.println();// 发一个空行，表示请求头结束
			pw.flush();
			FileInputStream fin = new FileInputStream(f);

			BufferedReader r = new BufferedReader(new InputStreamReader(fin, "utf-8"));
			String line = null;
			while ((line = r.readLine()) != null) {
				pw.println(line);
				// pw.flush();
			}
			// byte[] b = new byte[(int) len];

			// fin.read(b);
			fin.close();
			// pw.write(new String(b));
			pw.flush();
		} catch (Exception e) { 
			e.printStackTrace();
		} finally {
			try {
				s.close();
			} catch (Exception e) { 
				e.printStackTrace();
			}
		}

	}
}